import 'dart:async';

import 'package:flutter/material.dart';
import 'package:gold/base/config.dart';
import 'package:gold/http/api_login.dart';
import 'package:gold/http/api_shop.dart';
import 'package:gold/http/apis.dart';
import 'package:gold/http/http.dart';
import 'package:gold/model/gold_price_model.dart';
import 'package:gold/model/shop_model.dart';
import 'package:gold/model/user_model.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/cache_data.dart';

/// @description: 用户信息全局状态
/// @author tangzhentao
/// @created at 19:47 2022/6/17

class UserProvider extends ChangeNotifier {
  /// 是否登录
  late bool _isLogin = CacheData().authorization.isNotEmpty == true;
  bool get isLogin => _isLogin;
  set isLogin(bool state) {
    if (_isLogin != state) {
      _isLogin = state;
    }
  }

  /// 用户信息
  UserModel _user = CacheData().userInfo;
  UserModel get user => _user;

  /// 实时金价计时器
  Timer? _timer;

  /// 实时金价
  GoldQuotes? _goldQuotes;
  GoldQuotes? get goldQuotes => _goldQuotes;

  /// 登录成功更新
  Future loginSuccessUpdate(String authorization) async {
    await CacheData().setLoginSuccess(authorization);
    _isLogin = true;
    notifyListeners();
  }

  /// 退出登录
  Future signOut({bool toLogin = true}) async {
    if (!_isLogin) return;
    _isLogin = false;
    _user = UserModel();
    await CacheData().setSignOut();
    await CacheData().setUser(_user);
    notifyListeners();
    if (toLogin) XfgNav.popUntil(Routes.root);
  }

  /// 更新用户积分
  void updatePoint(int point) {
    _user = _user.copyWith();
    _user.points = point;
    notifyListeners();
  }

  /// 更新用户资料
  Future updateProfile() async {
    final result = await Http().request<UserModel>(ApiLogin.userProfile, showErrorMsg: false);
    if (result.success && result.data != null) {
      await CacheData().setUser(result.data!);
      _user = CacheData().userInfo;
      notifyListeners();
    }
  }

  /// 用户信息
  ShopModel _shop = CacheData().shopInfo;
  ShopModel get shop => _shop;

  /// 是否店主
  bool isShopOwner() => user.role != UserRole.shopOwner;

  /// 更新店铺信息
  Future updateShopInfo() async {
    if (isShopOwner()) {
      final result = await Http().request<ShopModel>(ApiShop.statistics, showErrorMsg: false);
      if (result.success && result.data != null) {
        await CacheData().setShop(result.data!);
        _shop = CacheData().shopInfo;
        notifyListeners();
      }
    }
  }

  /// 启动实时金价计时器
  void _startGoldQuotesTimer() async {
    _timer?.cancel();
    _timer = null;
    await Future.delayed(const Duration(seconds: 1));
    await requestGoldRealTimeQuotes();
    _timer = Timer.periodic(const Duration(minutes: 60), (_) {
      requestGoldRealTimeQuotes();
    });
  }

  /// 请求实时金价
  Future requestGoldRealTimeQuotes() async {
    final result = await Http().request<GoldPriceModel>(Apis.goldPrice, data: {
      'goldid': '1301,1051,1053,1054,1055,1056,1057,1058,1059,1060'
    }, showErrorMsg: false);
    final data = result.data?.result?.dtList;
    if (result.success && data?.isNotEmpty == true) {
      DateTime maxDate = DateTime(1900);
      String? dateDes;
      data!.forEach((key, dt) {
        final desc = dt.uptime;
        final date = DateTime.parse(desc?? '1900-01-01 00:00:00');
        if (date.isAfter(maxDate)) {
          maxDate = date;
          dateDes = desc;
        }
      });
      _goldQuotes = GoldQuotes(dateDes, data);
      notifyListeners();
    }
    // else {
    //   if (result.data?.success == 0 && result.data?.msgid == 1000572) {
    //     _timer?.cancel();
    //     _timer = null;
    //   }
    // }
  }

  @override
  void dispose() {
    _timer?.cancel();
    _timer = null;
    super.dispose();
  }
}

class GoldQuotes {
  final String? date;
  final Map<String, GoldPriceResultDt> map;

  GoldQuotes(this.date, this.map);
}